import React, { useEffect, useRef, useCallback } from 'react';
import * as echarts from 'echarts';
import { MapChart } from 'echarts/charts';
import chinaMapData from './china.js'; // 引入中国地图数据

// 按需引入 MapChart 组件
echarts.use([MapChart]);

const ConsultationTotalMap = () => {
  const mapRef = useRef(null);
  const chartInstance = useRef(null);

  const initChinaMap = useCallback(() => {
    if (!mapRef.current) return;
    
    // 检查元素大小
    console.log('Map container size:', mapRef.current.offsetWidth, mapRef.current.offsetHeight);
    
    // 使用 getInstanceByDom 获取已有实例或创建新实例
    const renderedInstance = echarts.getInstanceByDom(mapRef.current);
    if (renderedInstance) {
      chartInstance.current = renderedInstance;
    } else {
      chartInstance.current = echarts.init(mapRef.current);
    }

    // 注册中国地图数据
    echarts.registerMap('china', chinaMapData);

    // 获取数据中的最大值用于 visualMap
    const mapData = getMapData();
    const maxValue = Math.max(...mapData.map(item => item.value));

    // 地图配置选项
    const option = {
      title: {
        text: '全国咨询量分布图',
        left: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 24
        }
      },
      tooltip: {
        trigger: 'item',
        showDelay: 0,
        transitionDuration: 0.2,
        formatter: function(params) {
          return `${params.name}: ${params.value || 0} 次`;
        },
        backgroundColor: 'rgba(6, 33, 68, 0.9)',
        borderColor: '#24bbec',
        textStyle: {
          color: '#fff',
          fontSize: 18
        }
      },
      visualMap: {
        type: 'continuous',
        left: 'left',
        bottom: '20',
        min: 0,
        max: maxValue,
        inRange: {
          color: ['#1a4d87', '#24bbec', '#ffc640', '#ff6b6b']
        },
        textStyle: {
          color: '#e6f7ff',
          fontSize: 16
        },
        text: [`最大值: ${maxValue}`, '0']
      },
      toolbox: {
        show: true,
        left: 'right',
        top: 'top',
        feature: {
          restore: {},
          saveAsImage: {}
        }
      },
      series: [{
        name: '咨询量',
        type: 'map',
        map: 'china', // 使用china地图
        roam: false,
        zoom: 1.2,
        label: {
          show: true,
          color: '#fff',
          fontSize: 14
        },
        emphasis: {
          label: {
            show: true,
            color: '#fff',
            fontSize: 16
          },
          itemStyle: {
            areaColor: '#ffa022'
          }
        },
        data: mapData
      }]
    };

    // 设置图表选项
    chartInstance.current.setOption(option, true);
    
    // 检查是否成功设置选项
    console.log('ECharts option set successfully');
  }, []);

  useEffect(() => {
    // 延迟初始化以确保DOM已挂载
    const timer = setTimeout(() => {
      if (mapRef.current) {
        initChinaMap();
      }
    }, 100);

    const handleResize = () => {
      if (chartInstance.current) {
        chartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      clearTimeout(timer);
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }
    };
  }, [initChinaMap]);

  // 生成地图数据（模拟数据）
  const getMapData = () => {
    const provinces = [
      {name: '北京', value: 12000},
      {name: '天津', value: 8500},
      {name: '上海', value: 15000},
      {name: '重庆', value: 9800},
      {name: '河北', value: 7500},
      {name: '河南', value: 11000},
      {name: '云南', value: 6800},
      {name: '辽宁', value: 9200},
      {name: '黑龙江', value: 7300},
      {name: '湖南', value: 10200},
      {name: '安徽', value: 8600},
      {name: '山东', value: 12500},
      {name: '新疆', value: 5800},
      {name: '江苏', value: 13800},
      {name: '浙江', value: 14200},
      {name: '江西', value: 7900},
      {name: '湖北', value: 11500},
      {name: '广西', value: 8100},
      {name: '甘肃', value: 5200},
      {name: '山西', value: 7600},
      {name: '内蒙古', value: 6200},
      {name: '陕西', value: 9000},
      {name: '吉林', value: 6900},
      {name: '福建', value: 10800},
      {name: '贵州', value: 6300},
      {name: '广东', value: 18000},
      {name: '青海', value: 3800},
      {name: '西藏', value: 2900},
      {name: '四川', value: 11700},
      {name: '宁夏', value: 4100},
      {name: '海南', value: 5600},
      {name: '台湾', value: 9500},
      {name: '香港', value: 7800},
      {name: '澳门', value: 3200}
    ];
    
    return provinces;
  };

  return (
    <div ref={mapRef} style={{ width: '100%', height: '100%' }}></div>
  );
};

export default ConsultationTotalMap;